<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="0px">
      <el-form-item label="" prop="Name">
        <el-input
          v-model="queryParams.Name"
          placeholder="请输入姓名"
          clearable
          style="width: 240px;"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="" prop="Mobile">
        <el-input
            v-model="queryParams.Mobile"
            placeholder="请输入手机号"
            clearable
            style="width: 240px;"
            @keyup.enter="handleQuery"
        />
      </el-form-item>

      <el-form-item label="" prop="Created" style="width: 240px;">
          <el-date-picker
              v-model="dateRange"
              value-format="YYYY-MM-DD"
              type="daterange"
              range-separator="-"
              start-placeholder="创建开始日期"
              end-placeholder="创建结束日期"
          ></el-date-picker>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-col>
<!--        <el-button-->
<!--          type="primary"-->
<!--          plain-->
<!--          icon="Plus"-->
<!--          @click="handleAdd"-->
<!--          v-hasPermi="['member:Member:add']"-->
<!--        >新增</el-button>-->
<!--      </el-col>-->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="success"-->
<!--          plain-->
<!--          icon="Edit"-->
<!--          :disabled="single"-->
<!--          @click="handleUpdate"-->
<!--          v-hasPermi="['member:Member:edit']"-->
<!--        >修改</el-button>-->
<!--      </el-col>-->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="danger"-->
<!--          plain-->
<!--          icon="Delete"-->
<!--          :disabled="multiple"-->
<!--          @click="handleDelete"-->
<!--          v-hasPermi="['member:Member:remove']"-->
<!--        >删除</el-button>-->
<!--      </el-col>-->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="warning"-->
<!--          plain-->
<!--          icon="Download"-->
<!--          @click="handleExport"-->
<!--          v-hasPermi="['member:Member:export']"-->
<!--        >导出</el-button>-->
<!--      </el-col>-->

      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
    </el-row>

    <el-table height="calc(100vh - 300px)" stripe="true"  v-loading="loading" :data="memberList" @selection-change="handleSelectionChange">
<!--      <el-table-column type="selection" width="55" align="center"></el-table-column>-->
      <el-table-column label="编号" align="center" prop="Id" v-if="columns[0].visible" />
      <el-table-column label="头像" align="center" prop="avatar" width="80" v-if="columns[1].visible" >
        <template #default="scope">
          <image-preview :src="scope.row.avatar" :width="50" :height="50" />
        </template>
      </el-table-column>
      <el-table-column label="姓名" align="center" prop="Name" v-if="columns[2].visible" />
      <el-table-column label="手机号" align="center" prop="Mobile" v-if="columns[3].visible" />
      <el-table-column label="车牌号" align="center" prop="LicencePlate" v-if="columns[4].visible" />
      <el-table-column label="驾驶证" align="center" prop="DriverLicence" v-if="columns[5].visible" />
      <el-table-column label="openid" align="center" prop="Openid" v-if="columns[6].visible" />
      <el-table-column label="创建时间" align="center" prop="Created" v-if="columns[7].visible" >
        <template #default="scope">
          <span>{{ parseTime(scope.row.Created, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
<!--      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">-->
<!--        <template #default="scope">-->
<!--          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['member:Member:edit']">修改</el-button>-->
<!--          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['member:Member:remove']">删除</el-button>-->
<!--        </template>-->
<!--      </el-table-column>-->
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改用户对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="MemberRef" :model="form" :rules="rules" label-width="80px">
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Member">
import { listMember, getMember, delMember, addMember, updateMember } from "@/api/merchant/member";

const { proxy } = getCurrentInstance();

const memberList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const dateRange = ref([]);

let newList = [];

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    Name: null,
    LicencePlate: null,
    DriverLicence: null,
    Mobile: null,
    Created: null,
  },
  rules: {
  }
});

// 列显隐信息
const columns = ref([
  { key: 0, label: `编号`, visible: false },
  { key: 1, label: `头像`, visible: true },
  { key: 2, label: `姓名`, visible: true },
  { key: 3, label: `手机号`, visible: true },
  { key: 4, label: `车牌号`, visible: true },
  { key: 5, label: `驾驶证`, visible: true },
  { key: 6, label: `openid`, visible: false },
  { key: 7, label: `创建时间`, visible: true }
]);

const { queryParams, form, rules } = toRefs(data);


/** 查询用户列表 */
function getList() {
  loading.value = true;
  listMember(proxy.addDateRange(queryParams.value, dateRange.value)).then(response => {
    memberList.value = response.rows;
    newList = response.rows;

    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  dateRange.value = [];
  form.value = {
    Id: null,
    Name: null,
    LicencePlate: null,
    DriverLicence: null,
    Mobile: null,
    OpenId: null,
    Created: null,
  };
  proxy.resetForm("MemberRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.Id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加用户";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _Id = row.Id || ids.value
  getMember(_Id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改用户";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["MemberRef"].validate(valid => {
    if (valid) {
      if (form.value.Id != null) {
        updateMember(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addMember(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _Ids = row.Id || ids.value;
  proxy.$modal.confirm('是否确认删除用户编号为"' + _Ids + '"的数据项？').then(function() {
    return delMember(_Ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('member/Member/export', {
    ...queryParams.value
  }, `Member_${new Date().getTime()}.xlsx`)
}

function getTextWidth (str) {
  let width = 0
  const html = document.createElement('span')
  html.innerText = str
  html.className = 'getTextWidth'
  document.querySelector('body').appendChild(html)
  width = document.querySelector('.getTextWidth').offsetWidth
  document.querySelector('.getTextWidth').remove()
  return width
}

//遍历列的所有内容，获取最宽一列的宽度
function getMaxLength (arr) {
  return arr.reduce((acc, item) => {
    if (item) {
      const calcLen = getTextWidth(item)
      if (acc < calcLen) {
        acc = calcLen
      }
    }
    return acc
  }, 0)
}

/**
 * el-table-column 自适应列宽
 * @param prop_label: 表名
 * @param table_data: 表格数据
 */

function flexColumnWidth (label, prop) {
// 1.获取该列的所有数据
  const arr = newList.map(x => x[prop])
// 把每列的表头也加进去算
  arr.push(label)
// 2.计算每列内容最大的宽度 + 表格的内间距（依据实际情况而定）
  return (getMaxLength(arr) + 40) + 'px';
}

const pickerOptions = {
  shortcuts: [
    {
      text: '最近一小时',
      onClick(picker) {
        const end = new Date(); // 结束时间为当前时间
        const start = new Date(end.getTime() - 3600000); // 开始时间为当前时间减去一小时
        picker.$emit('pick', [start, end]);
      }
    },
    {
      text: '今日',
      onClick(picker) {
        const start = new Date();
        start.setHours(0, 0, 0, 0); // 设置为00:00:00
        const end = new Date();
        end.setHours(23, 59, 59, 999); // 设置为23:59:59
        picker.$emit('pick', [start, end]);
      }
    },
    {
      text: '昨日',
      onClick(picker) {
        const start = new Date();
        start.setDate(start.getDate() - 1); // 设置为昨天
        start.setHours(0, 0, 0, 0); // 设置为00:00:00
        const end = new Date();
        end.setDate(end.getDate() - 1);
        end.setHours(23, 59, 59, 999); // 设置为23:59:59
        picker.$emit('pick', [start, end]);
      }
    },
    {
      text: '本月',
      onClick(picker) {
        const start = new Date();
        start.setDate(1); // 设置为本月的第一天
        start.setHours(0, 0, 0, 0); // 设置为00:00:00
        const end = new Date(); // 本月的今天
        end.setHours(23, 59, 59, 999); // 设置为23:59:59
        picker.$emit('pick', [start, end]);
      }
    },
    {
      text: '上个月',
      onClick(picker) {
        const start = new Date();
        start.setMonth(start.getMonth() - 1); // 设置为上个月的第一天
        start.setDate(1);
        start.setHours(0, 0, 0, 0); // 设置为00:00:00
        const end = new Date();
        end.setDate(0); // 设置为上个月的最后一天
        end.setHours(23, 59, 59, 999); // 设置为23:59:59
        picker.$emit('pick', [start, end]);
      }
    }, {
      text: '最近一周',
      onClick(picker) {
        const end = new Date();
        const start = new Date();
        start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
        start.setHours(0, 0, 0, 0); // 设置为00:00:00
        end.setHours(23, 59, 59, 999); // 设置为23:59:59
        picker.$emit('pick', [start, end]);
      }
    }, {
      text: '最近一个月',
      onClick(picker) {
        const end = new Date();
        const start = new Date();
        start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
        start.setHours(0, 0, 0, 0); // 设置为00:00:00
        end.setHours(23, 59, 59, 999); // 设置为23:59:59
        picker.$emit('pick', [start, end]);
      }
    }, {
      text: '最近三个月',
      onClick(picker) {
        const end = new Date();
        const start = new Date();
        start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
        start.setHours(0, 0, 0, 0); // 设置为00:00:00
        end.setHours(23, 59, 59, 999); // 设置为23:59:59
        picker.$emit('pick', [start, end]);
      }
    }]
}

getList();
</script>
<style lang="scss" scoped>
.el-form-item {
  margin-bottom: 4px !important;
}

.el-form--inline .el-form-item {
  margin-right: 0px;
}
//.el-form-item {
//  width: 192px;
//}
.el-input{
  margin-right: 10px;
}
</style>